<?php
/**
 * Fix Companies :
 * Keyname & Duplicates
 * 
 */

use Fox\Dao\SqlFragment;
use Hive\Company;
use Fox\Html\CheckBox;
use Fox\Html\Screen;
use Fox\Html\Block;
use Fox\Html\Input;
use Fox\Html\Interval;

$screen = new Screen('sCompanies','execute');
$screen->pageTitle('Fix Company Keyname');
$block = new Block('bExec','Parameters');
$block->add(new Interval('compid',false));
$block->add(new CheckBox('commit',false));
$block->add(new Input('dbcnt',true,100));
$screen->add($block);
if($screen->submitted()) {
	
	$fields = $screen->get();
	if(!$screen->errors()) 
	{
		$commit = $fields['commit'];
		$fragments = $block->item('compid')->fragments();
		$finder = new Company();
		$companies = $finder->find(SqlFragment::combine($fragments),null,null,$fields['dbcnt']);
		foreach($companies as $company) {
			$keyname = Company::cleanup($company->company_name);
			if($company->keyname != $keyname) {
				$company->keyname = $keyname;
				$company->prepareUpdate(Company::CHANGE_DEFAULT);
				try {
					if($commit) {
						$company->update();
					}
					Fox\Message::Success($company->company_name.' has been updated : '.$company->company_keyname.' -> '.$company->keyname);
				} catch(Fox\Object\Exception\Save $e) {
					Fox\Message::Error(e);
				}
			}
		}
	}
}
echo $screen->display();